package com.shipwe.loans.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentStepAuthWalletBinding
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityAuthSteps
import com.shipwe.loans.ui.adapter.AuthStepWalletAdapter
import com.shipwe.loans.ui.presenter.AuthStepWalletPresenter
import com.shipwe.loans.ui.view.IAuthStepWalletView
import com.shipwe.loans.utils.dialog.AuthWalletAddDialog
import com.shipwe.loans.utils.dialog.AuthWalletDeleteDialog
import com.shipwe.loans.utils.dialog.AuthWalletOtherDialog
import com.shipwe.loans.utils.dialog.AuthWalletSubmitDialog
import com.shipwe.loans.utils.dialog.AuthWalletSubmitWarningDialog
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class FragmentStepAuthWallet(): ShipweFragment(),IAuthStepWalletView {
    lateinit var binding: FragmentStepAuthWalletBinding
    private var stepItem: JSONObject? = null
    private var eventRemark = ""
    var presenter: AuthStepWalletPresenter? = null

    private var walletAdapter: AuthStepWalletAdapter? = null

    constructor(stepItem: JSONObject): this(){
        eventRemark = stepItem.optString("stepTitle")
        this.stepItem = stepItem
    }

    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentStepAuthWalletBinding.inflate(inflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        if (stepItem != null){
            binding.authStepTitle.text = stepItem!!.optString("showTitle")
        }
        initAuthStepWalletListView()

        //积分
        binding.walletAddPoints.text = String.format(getString(R.string.points_add_count), CustomConfigsHelper.getShipweAddWalletPoints())
    }

    override fun initShipweListener() {
        //添加
        binding.walletAdd.setOnClickListener {
            showBinCardAddDialog()
        }

        //提交
        binding.walletNext.setOnClickListener {
            if (!isStepSubmit()){
                showErrorTipsDialog(getString(R.string.dialog_tips_submit_error), eventRemark)
                return@setOnClickListener
            }
            onCheckSubmitStatus()
        }
    }

    override fun initShipweData() {
        presenter = AuthStepWalletPresenter(this)
        presenter!!.requestAuthStepWalletListAction()
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepWalletListView(){
        binding.walletListView.isNestedScrollingEnabled = false
        binding.walletListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.walletListView.layoutManager = layoutManager
        walletAdapter = AuthStepWalletAdapter(binding.walletListView)
        binding.walletListView.adapter = walletAdapter!!
        binding.walletListView.itemAnimator = DefaultItemAnimator()
        walletAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = walletAdapter!!.getItem(position)
            when(childView.id){
                R.id.walletEdit -> {//添加
                    showBinCardAddDialog()
                }
                R.id.walletDelete -> {//删除
                    showDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    override fun showAuthStepWalletList(accountList: ArrayList<JSONObject>) {
        walletAdapter!!.data = accountList

        //最多添加10个账户
        if (walletAdapter!!.itemCount >= 10){
            binding.walletAdd.isEnabled = false
            binding.walletAddLayout.visibility = View.GONE
        } else {
            binding.walletAdd.isEnabled = true
            binding.walletAddLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showAuthStepWalletOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = AuthWalletOtherDialog(requireContext(),eventRemark,object : AuthWalletOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletOtherConfirm){//添加
                    presenter!!.onSunmitAuthStepWalletAddAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBinCardAddDialog(){
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_ADD,eventRemark)
        val bindCardDialog = AuthWalletAddDialog(requireContext(),eventRemark,object : AuthWalletAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter!!.onSunmitAuthStepWalletAddAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showSubmitWarningDialog(){
        val warningDialog = AuthWalletSubmitWarningDialog(requireContext(),eventRemark,object : AuthWalletSubmitWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.walletWarningNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        val act = getAct() as ActivityAuthSteps
                        act.showAuthStepsSubmitSuccess()
                    }
                    R.id.walletWarningAdd -> {//继续添加
                        showBinCardAddDialog()
                    }
                }
            }
        })
        warningDialog.setCancelable(true)
        warningDialog.setCanceledOnTouchOutside(true)
        warningDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showConfirmDialog(){
        val submitDialog = AuthWalletSubmitDialog(requireContext(),object : AuthWalletSubmitDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletSubmit){
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                    // TODO: 发送通知，更新主流程
                    val act = getAct() as ActivityAuthSteps
                    act.showAuthStepsSubmitSuccess()
                }
            }
        })
        submitDialog.show()
        submitDialog.setBindAccountList(walletAdapter!!.data)
    }

    /**
     * 删除提示
     */
    private fun showDeleteDialog(item: JSONObject){
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = AuthWalletDeleteDialog(requireContext(),eventRemark, object : AuthWalletDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletDeleteConfirm){
                    presenter!!.onDeleteAuthStepWalletAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isStepSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        for (i in 0..<walletAdapter!!.itemCount){
            //存在一个不是编辑状态的item，则可以提交
            if (!walletAdapter!!.getItem(i).optBoolean("isEdit",true)){
                submitIsEnabled = true
                break
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun onCheckSubmitStatus(){
        var count = 0
        walletAdapter!!.data.forEach {
            //不是编辑类型
            if (!it.optBoolean("isEdit",true)){
                count += 1
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showConfirmDialog()
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_ACCOUNT_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_ACCOUNT_END)
    }
}